package com.lxhdj.common.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BeanUtil {


    /**
     * 对象转换为指定的对象
     * @param obj
     * @param clazz
     * @return
     * @param <T>
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public static <T> T convert(Object obj, Class<T> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        T t = clazz.getDeclaredConstructor().newInstance();
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            // 获取属性名
            String name = method.getName();
            if (name.startsWith("get") && !name.equals("getClass")) {
                name = name.substring(3);
//                name = name.substring(0, 1).toLowerCase() + name.substring(1);
                // 获取属性值
                Object value = method.invoke(obj);
                // 设置属性值
                Method setMethod = clazz.getMethod("set" + name, method.getReturnType());
                setMethod.invoke(t, value);
            }
        }
        return t;
    }
}
